using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class PlayerController : MonoBehaviour
{
    private NavMeshAgent _agent;
    private Animator _animator;

    private GameObject attackTarget;
    private float lastAttackTime;
    
    private void Awake()
    {
        _agent = GetComponent<NavMeshAgent>();
        _animator = GetComponent<Animator>();
    }

    private void Start()
    {
        MouseManager.Instance.OnMouseClicked += MoveToTarget;
        MouseManager.Instance.OnEnemyClicked += EventAttack;
    }

    private void OnDestroy()
    {
        MouseManager.Instance.OnMouseClicked -= MoveToTarget;
        MouseManager.Instance.OnEnemyClicked -= EventAttack;
    }

    private void Update()
    {
        switchAnimation();

        lastAttackTime -= Time.deltaTime;
    }

    private void switchAnimation()
    {
        _animator.SetFloat("Speed", _agent.velocity.sqrMagnitude);
    }

    public void MoveToTarget(Vector3 target)
    {
        StopCoroutine(nameof(MoveToAttackTarget));
        _agent.isStopped = false;
        _agent.destination = target;
    }

    private void EventAttack(GameObject obj)
    {
        if (obj == null)
        {
            return;
        }

        attackTarget = obj;

        StartCoroutine(nameof(MoveToAttackTarget));
    }

    IEnumerator MoveToAttackTarget()
    {
        _agent.isStopped = false;

        transform.LookAt(attackTarget.transform);
        
        // FIXME: adjust attack range
        while (Vector3.Distance(transform.position, attackTarget.transform.position) > 1)
        {
            _agent.destination = attackTarget.transform.position;
            yield return null;
        }

        _agent.isStopped = true;
        if (lastAttackTime < 0)
        {
            _animator.SetTrigger("Attack");
            lastAttackTime = 0.5f;
        }
    }
}
